<template>
    <el-row :gutter="20">
        <el-col v-loading="loading" :span="6">
            <el-card>
                <el-input v-model="filterText" placeholder="请输入关键字">
                    <template #append>
                        <el-button icon="Search" />
                    </template>
                </el-input>
                <el-tree @node-click="nodeTreehandle" class="mt" ref="treeRef" style="max-width: 600px" :data="treeData" :props="defaultProps"
                   :filter-node-method="filterNode" />
            </el-card>
        </el-col>
        <el-col :span="18">
            <el-card>
                <template #header>
                    <div class="card-header">
                        <span>{{ title }}:计费模板</span>
                    </div>
                </template>
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100">
                    <el-form-item label="模板名称：" prop="name">
                        <el-input v-model="ruleForm.name" placeholder="请输入模板名称" style="width: 200px;" :disabled="!title"></el-input>
                    </el-form-item>
                    <el-form-item style="margin-left: -10px;" :label="'时间区间' + (index + 1) + ':'"
                        v-for="(timeSlot, index) in ruleForm.data" :key="index">
                        <el-col :span="17">
                            <el-form-item :prop="'data.' + index + '.date'"
                                :rules="[{ required: true, message: '时间区间不可以为空', trigger: 'blur' }, { validator: validatePass, trigger: 'blur' }]">
                                <el-time-picker style="width: 800px;" v-model="timeSlot.date" is-range
                                    range-separator="To" start-placeholder="开始时间" end-placeholder="结束时间"
                                    value-format="HH:mm:ss" :disabled="!title"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="电费：" :prop="'data.' + index + '.electricity'"
                                :rules="{ validator: validateNumber, trigger: 'blur' }">
                                <el-input v-model="timeSlot.electricity" placeholder="请输入电费" :disabled="!title"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-form-item>

                    <el-form-item>
                        <el-button @click="addTimeSlot" type="primary" :disabled="!title">添加区间</el-button>
                    </el-form-item>

                    <el-form-item label="服务区：" prop="service">
                        <el-input v-model="ruleForm.service" placeholder="请输入服务费" :disabled="!title"> </el-input>
                    </el-form-item>

                    <el-form-item label="停车费：" prop="parking">
                        <el-input v-model="ruleForm.parking" placeholder="请输入停车费" :disabled="!title"></el-input>
                    </el-form-item>

                    <el-form-item label="特殊备注：" prop="remarks">
                        <el-input v-model="ruleForm.remarks" placeholder="您是否要写入备注信息" type="textarea" :disabled="!title"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="handleAdd" :disabled="!title">创建</el-button>
                        <el-button @click="resetForm" :disabled="!title">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </el-col>
    </el-row>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { getCityListAPI } from '@/api/operation'
import { checkTimeRange } from '@/utils/isCheckTimeRange'
import { ElMessage } from 'element-plus'
import type { TreeInstance, FormInstance, FormRules } from 'element-plus'
const treeRef = ref<TreeInstance>()
// tree树形的属性
interface Tree {
    label: string,
    children?: Tree[]
}
const defaultProps = {
    children: 'children',
    label: 'label'
}
interface RuleFormType {
    name: string,
    service: string,
    parking: string,
    remarks: string,
    data?: Array<{ date: any, electricity: string }>
}
const loading = ref<boolean>(false)
// 模糊匹配
const filterText = ref<string>('')
const treeData = ref<Tree[]>([])
const loadData = async () => {
    try {
        loading.value = true
        const { data } = await getCityListAPI()
        treeData.value = data
        console.log(data)
    } catch (error) {
        console.error(error)
    } finally {
        loading.value = false
    }
}
onMounted(async () => {
    loadData()
})

// 模糊查询
watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
    if (!value) return true
    return data.label.includes(value)
}

// 计费模板部分
const title = ref<string>('')
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleFormType>>({
    name: [
        { required: true, message: '请输入模板名称', trigger: 'blur' }
    ],
    service: [
        { required: true, message: '请输入模板名称', trigger: 'blur' }
    ],
    parking: [
        { required: true, message: '请输入模板名称', trigger: 'blur' }
    ],
    remarks: [
        { required: true, message: '请输入模板名称', trigger: 'blur' }
    ]
})
const ruleForm = ref<RuleFormType>({
    name: '',
    service: '',
    parking: '',
    remarks: '',
    data: [
        { date: '', electricity: '' }
    ]
})
// 添加时间区间
const addTimeSlot = () => {
    ruleForm.value.data?.push({ date: '', electricity: '' })
}
// 时间区间正则校验
const validatePass = (rule: any, value: any, callback: any) => {
    // 获取当前列表中最后一个值进行比较
    const real1 = ruleForm.value?.data?.slice(-1)[0]?.date[0]
    const real2 = ruleForm.value?.data?.slice(-1)[0]?.date[1]
    // 把格式变为---{data1:item.date[0],data2:item.date[1]}
    const dateAll = ruleForm.value?.data?.map((item: any) => ({ data1: item.date[0], data2: item.date[1] }))
    const filterData = dateAll?.filter((item) => item.data1 != real1 && item.data2 != real2)
    let flag;
    // 如果列表中只要一个就无需进行判断，如果有就进行正则判断
    if (dateAll?.length != 1) {
        flag = checkTimeRange(real1, real2, filterData)
    }
    if (flag) {
        callback(new Error(flag))

    } else {
        callback()
    }

}
// 是否是纯数字校验
const validateNumber = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('电费不可以为空'))
    }
    const isNumber = /^[^0]\d+$/
    if (isNumber.test(value)) {
        callback()
    }
    callback(new Error('不是纯数字，或以0开头'))
}
// 新增计费模板
const handleAdd = () => {
    ruleFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            ElMessage({
                message: '新增计费模板成功',
                type: 'success',
                plain: true,
            })
            await loadData()
            resetForm()
        }
    })
}
// 重置表单
const resetForm = () => {
    ruleFormRef.value?.resetFields()
}
const nodeTreehandle =(value:Tree)=>{
    if(!value.children){
        title.value = value.label
    }
    resetForm()
}
</script>